package com.hrsystem.controller;

import com.hrsystem.common.Res;
import com.hrsystem.entity.FileInfo;
import com.hrsystem.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: zhuxm
 * Date: 2021/6/13
 * Time: 13:28
 */
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 文件上传接口
     *
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public Res upload(MultipartHttpServletRequest request) {
        Iterator<String> fileNames = request.getFileNames();
        List<FileInfo> fileList = new ArrayList<>();
        while (fileNames.hasNext()) {
            MultipartFile multipartFile = request.getFile(fileNames.next());
            FileInfo fileInfo = fileService.upload(multipartFile);
            fileList.add(fileInfo);
        }
        if (fileList.size() == 1) {
            return new Res(1, "上传成功", fileList.get(0));
        } else {
            return new Res(1, "上传成功", fileList);
        }
    }

    /**
     * 文件下载接口
     *
     * @param md5
     * @param response
     */
    @GetMapping("/{md5}")
    public void download(@PathVariable("md5") String md5, HttpServletResponse response) {
        fileService.download(response, md5);
    }
}
